/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: message_queue.h
 *
 * Purpose: message queue API define and implmenetation
 *
 * Developer:
 *   wen.gu , 2023-06-28
 *
 * TODO:
 *
 ***************************************************************************/

#ifndef __UDSSIPC_MESSAGE_QUEUE_H__
#define __UDSSIPC_MESSAGE_QUEUE_H__

#include <string>
#include <memory>
#include <condition_variable>
#include <mutex>

#include "core/udssipc_type.h"
#include "core/com_message.h"



class MessageQueue final {
public:
    using MessageQueuePtr = std::shared_ptr<MessageQueue>;
public:
    MessageQueue(uint32_t max_limit = 0); /** if set as 0, inidicate unlimited this size */
    ~MessageQueue();

public:
    ComErrC push(ComMessagePtr msg_ptr);
    /** timeout_ms: see also 'class Timeout',
     * NoWait: if the queue is emptry, then return immediately.
     * WaitForever: if the queue is emptry, then the pop() will be block until got new message or the queue is stopped.
     * > 0 : if the queue is emptry, then the pop() will be block until got new message or timeout or the queue is stopped.
    */
    ComMessagePtr pop(int32_t timeout_ms = Timeout::WaitForever); 
    uint32_t size() const;
    void clear();
    bool empty();
    bool is_stopped() const { return !is_started_; }
public:
    ComErrC start();
    ComErrC stop();
private:
    struct MsgNode {
        MsgNode* next = nullptr;
        ComMessagePtr msg = nullptr;
    };

    bool is_started_ = true;
    uint32_t size_ = 0; /** how many msg in queue*/
    uint32_t max_size_limited_ = 0;
    MsgNode* list_head_ = nullptr;
    MsgNode* list_tail_ = nullptr;

    std::mutex lock_;
    std::condition_variable cv_;
};

#endif /** !__UDSSIPC_MESSAGE_QUEUE_H__ */